package presenter;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
//            SongFile, SimpleVariableFile, Bible, SongVerse

public class Scheduler extends JPanel implements MouseListener, KeyListener, ActionListener
{
    public static final long serialVersionUID=123;
    ArrayList<SongFile> songs;
    SongFile song[];
    JList songList;
    JScrollPane scrollPane;
    Timer t;
    SongFile allSongs[];
    Bible bible;
    File f;
    boolean update;
    JPanel panel;
    JToolBar sidePanel;
    JButton up,down,remove;
    
    public Scheduler(SongFile allSongs[]) {
        this(null, allSongs,null);
    }

    public Scheduler(SongFile songs[], SongFile allSongs[], Bible bible) {
        super(new BorderLayout());
        this.allSongs = allSongs;
        this.songs = new ArrayList<SongFile>();
        this.bible=bible;
        if(songs != null) {
            for(int i = 0; i < songs.length; i++)
                this.songs.add(songs[i]);

        }
        song = (SongFile[])this.songs.toArray(new SongFile[1]);
        songList = new JList(song);
        songList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        panel=new JPanel(new BorderLayout());
        //panel.add(songList, BorderLayout.CENTER);
        sidePanel=new JToolBar(JToolBar.VERTICAL);
        ImageIcon icon = createImageIcon("Icons/up.png","moves items higher in the schedule");
        up=new JButton(icon);
        sidePanel.add(up);
        icon = createImageIcon("Icons/down.png","moves items lower in the schedule");
        down=new JButton(icon);
        icon = createImageIcon("Icons/remove.png","removes items from the schedule");
        sidePanel.add(down);
        remove=new JButton(icon);
        up.addActionListener(this);
        down.addActionListener(this);
        remove.addActionListener(this);
        sidePanel.add(remove);
        sidePanel.setBorderPainted(false);
        sidePanel.setEnabled(false);
        
        panel.add(sidePanel,BorderLayout.EAST);
        scrollPane = new JScrollPane();
        scrollPane.getViewport().setView(songList);
        scrollPane.setVisible(true);
        panel.add(scrollPane,BorderLayout.CENTER);
        add(panel,BorderLayout.CENTER);
        songList.addMouseListener(this);
        update = false;

        songList.addKeyListener(this);
        sidePanel.addKeyListener(this);
        t = new Timer(100, this);
        t.start();
    }

    public void setSchedule(File f, SongFile songs[], Bible b) {
        SimpleVariableFile svf = new SimpleVariableFile(f);
        this.songs = new ArrayList<SongFile>();
        bible = b;
        this.f = f;
        SongFile song = new SongFile("   ");
        for(int i = 0; i < svf.getNumberOfVariables(); i++) {
            if(svf.exists("SongColor"+i)) {
                String colors = svf.getVariable("SongColor"+i);
                //System.out.println(colors);
                int red = Integer.parseInt(colors.substring(1, colors.indexOf('G')));
                int green = Integer.parseInt(colors.substring(colors.indexOf('G') + 1, colors.indexOf('B')));
                int blue = Integer.parseInt(colors.substring(colors.indexOf('B') + 1, colors.length()));
                Color color = new Color(red, green, blue);
                song.setColor(color);
            }
            if(svf.getVariable((new StringBuilder()).append("Song").append(i).toString()).equals("Scripture")) {
                if(svf.exists((new StringBuilder()).append("Scripture").append(i).toString())) {
                    SongVerse svs[];
                    if(svf.exists(("Bible")+i)&&!svf.getVariable(("Bible")+i).equals(""))
                        svs = BibleInformation.getBible(svf.getVariable(("Bible")+i)).getVerses(svf.getVariable((new StringBuilder()).append("Scripture").append(i).toString()));
                    else
                        svs= BibleInformation.getDefaultBible().getVerses(svf.getVariable((new StringBuilder()).append("Scripture").append(i).toString()));
                    SongFile scripture = new SongFile(svs[0].getType());
                    scripture.setScriptureString(svf.getVariable((new StringBuilder()).append("Scripture").append(i).toString()));
                    scripture.setScripture(true);
                    scripture.setVerses(svs);
                    scripture.setTitle(scripture.getScriptureString());
                    this.songs.add(scripture);
                }
            } else {
                int id = Integer.parseInt(svf.getVariable((new StringBuilder()).append("Song").append(i).toString()));
                if(svf.exists((new StringBuilder()).append("SongVideo").append(i).toString())) {
                    String vid = svf.getVariable((new StringBuilder()).append("SongVideo").append(i).toString());
                    String title = vid.substring(0, vid.lastIndexOf("."));
                    SongFile video = new SongFile(title);
                    video.setVideo(vid);
                    this.songs.add(video);
                }
                for(int j = 0; j < songs.length; j++) {
                    if(songs[j].getNumber() != id)
                        continue;
                    if(svf.exists((new StringBuilder()).append("SongVideo").append(i).toString())) {
                        song = songs[j];
                        song.setVideo(svf.getVariable((new StringBuilder()).append("SongVideo").append(i).toString()));
                        this.songs.add(song);
                    } else {
                        this.songs.add(songs[j]);
                    }
                }

            }
            if(svf.exists((new StringBuilder()).append("SongBackground").append(i).toString()))
                song.setBackground(svf.getVariable((new StringBuilder()).append("SongBackground").append(i).toString()));
        }

        this.song = (SongFile[])this.songs.toArray(new SongFile[0]);
        songList.setListData(this.song);
        songList.setSelectedIndex(0);
        //addKeyListener(this);
    }

    public SongFile[] getSchedule() {
        return (SongFile[])songs.toArray(new SongFile[1]);
    }

    public void setSchedule(SongFile song[]) {
        for(int i = 0; i < song.length; i++)
            songs.add(song[i]);

        songList.setListData(song);
    }

    public void addSong(SongFile sf) {
        songs.add(sf);
        song = (SongFile[])songs.toArray(song);
        songList.setListData(song);
    }

    public SongFile getActive() {
        if(songs!=null&&songList.getSelectedIndex() != -1&&songs.size()>0)
            return (SongFile)songs.get(songList.getSelectedIndex());
        else
            return null;
    }

    public void nextSong() {
        if(songList.getSelectedIndex() < songs.size() - 1)
            songList.setSelectedIndex(songList.getSelectedIndex() + 1);
    }

    public boolean isUpdated()
    {
        if(update) {
            update = false;
            return true;
        } else {
            return false;
        }
    }

    public Scheduler clone() {
        Scheduler sc = new Scheduler((SongFile[])songs.toArray(new SongFile[1]), allSongs,bible);
        sc.setSchedule((SongFile[])songs.toArray(new SongFile[1]));
        sc.setSize(getSize());
        sc.setVisible(isVisible());
        return sc;
    }

    public void mouseClicked(MouseEvent mouseevent) {
    }

    public void mousePressed(MouseEvent arg0) {
        //System.out.println("Mouse Pressed");
        update = true;
        //addKeyListener(this);
    }

    public void mouseReleased(MouseEvent mouseevent) {
    }

    public void mouseEntered(MouseEvent mouseevent) {
    }

    public void mouseExited(MouseEvent mouseevent) {
    }

    public void keyTyped(KeyEvent keyevent) {
    }

    public void openSchedule() {
        JFileChooser fc = new JFileChooser(new File("./Schedules/"));
        fc.setSelectedFile(new File("Schedule.txt"));
        int returnVal = fc.showOpenDialog(this);
        if(returnVal == 0)
            setSchedule(fc.getSelectedFile(), allSongs, bible);
    }

    public void saveSchedule() {
        JFileChooser fc = new JFileChooser(new File("./Schedules/"));
        fc.setSelectedFile(new File("Schedule.txt"));
        int returnVal = fc.showSaveDialog(this);
        if(returnVal == 0) {
            File file = fc.getSelectedFile();
            SimpleVariableFile svf = new SimpleVariableFile();
            ArrayList<String> output = new ArrayList<String>();
            ArrayList<String> vars = new ArrayList<String>();
            int lim = 0;
            for(int i = 0; i < songs.size(); i++) {
                SongFile sf = (SongFile)songs.get(i);
                if(sf.hasVideo()) {
                    vars.add((new StringBuilder()).append("SongVideo").append(i).toString());
                    output.add(sf.getVideo());
                }
                if(sf.hasCustomBackground()) {
                    vars.add((new StringBuilder()).append("SongBackground").append(i).toString());
                    output.add(sf.getBackground());
                }
                if(sf.isScripture()) {
                    vars.add((new StringBuilder()).append("Scripture").append(i).toString());
                    output.add(sf.getScriptureString());
                    vars.add((new StringBuilder()).append("Song").append(i).toString());
                    output.add("Scripture");
                    vars.add("Bible"+i);
                    output.add(sf.getBible());
                } else {
                    vars.add((new StringBuilder()).append("Song").append(i).toString());
                    output.add((new StringBuilder()).append("").append(sf.getNumber()).toString());
                }
            }

            svf.update((String[])vars.toArray(new String[1]), (String[])output.toArray(new String[1]));
            svf.write(file);
        }
    }

    public void keyPressed(KeyEvent ke) {
        int x = ke.getModifiers();
        int key = ke.getKeyCode();
        //if(x == 2 && key == 83)
          //  saveSchedule();
        if(x == 0 && key == 127) {
            removeCurrent();
            
           
        }
        int index=songList.getSelectedIndex();
       // if(x == 2 && key == 79)
         //   openSchedule();
        if(x == 1 && key == 38) {
            shiftUp(songList.getSelectedIndex());
            songList.setSelectedIndex(index);
        }
        if(x == 1 && key == 40) {
            shiftDown(songList.getSelectedIndex());
            songList.setSelectedIndex(index);
        }
        if(x==0 &&key==38&&index>0) {
            //songList.setSelectedIndex(index-1);
            //System.out.println("going up");
        }    
        //System.out.println(songList.getMaxSelectionIndex());
     //   if(x==0 && key==40&&index<songList.getMaxSelectionIndex()-1) {
       //     songList.setSelectedIndex(index+1);
            //System.out.println("going down");
        //}
    }
    
    private void removeCurrent() {
        songs.remove(songList.getSelectedIndex());
        int pos=songList.getSelectedIndex()-1;
        song = songs.toArray(new SongFile[0]);
        songList.setListData(song);
        if(pos>=0)
            songList.setSelectedIndex(pos);
    }

    public void shiftDown(int index) {
        if(index < songs.size() - 1) {
            SongFile temp = (SongFile)songs.get(index);
            songs.set(index, songs.get(index + 1));
            songs.set(index + 1, temp);
            song = (SongFile[])songs.toArray(song);
            songList.setListData(song);
            songList.setSelectedIndex(index+1);
        }
    }

    public void shiftUp(int index) {
        if(index>0) {
            shiftDown(index - 1);
            songList.setSelectedIndex(index-1);
        }
    }

    public void keyReleased(KeyEvent keyevent) {
        update=true;
    }

    public void actionPerformed(ActionEvent event) {
        if (event.getSource()==up) {
            shiftUp(songList.getSelectedIndex());
        } else if (event.getSource()==down) {
            shiftDown(songList.getSelectedIndex());
        } else if(event.getSource()==remove) {
            removeCurrent();
        }
        
    }
    
    public boolean requestFocusInWindow() {
        boolean test=songList.requestFocusInWindow();
        update=true;
        return test;
    }
    
    public void addKeyListener(KeyListener listener) {
        songList.addKeyListener(listener);
    }

    public void setUpdated(boolean updated) {
        update=updated;
    }
    
    protected ImageIcon createImageIcon(String path, String description) {
        return new ImageIcon(Toolkit.getDefaultToolkit().getImage(path),description);
    }

}
